package com.quanyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.entity.RespClubOpenInfo;
import com.quanyan.club.entity.vo.resp.MyNewestClubCard;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.comment.response.LableBaseInfo;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.constants.MqConstants;
import com.quanyan.common.encrypt.Coder;
import com.quanyan.common.mail.EmailUtils;
import com.quanyan.common.utils.*;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.place.service.UserService;
import com.quanyan.platform.client.IGatherTagService;
import com.quanyan.platform.response.GatherTagItem;
import com.quanyan.platform.response.RespGatherTags;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.statium.api.resp.RespUserCategory;
import com.quanyan.statium.service.StadiumOpenService;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.*;
import com.quanyan.user.model.db.*;
import com.quanyan.user.model.vo.request.*;
import com.quanyan.user.model.vo.response.*;
import com.quanyan.user.model.vo.response.admin.RespAppVersionInfo;
import com.quanyan.user.model.vo.response.my.ClubInfo;
import com.quanyan.user.model.vo.response.my.UserIndex;
import com.quanyan.user.mq.Producer.UserTaskMsgClientImpl;
import com.quanyan.user.mq.UserUpdateNotifyMsg;
import com.quanyan.user.request.ReqChangePhone;
import com.quanyan.user.service.*;
import com.quanyan.user.thread.UserInformationPerfectDegreeThread;
import com.quanyan.user.utils.IDCard;
import com.quanyan.user.utils.LarkCodeUtil;
import com.quanyan.user.utils.ThreadPoolSingleton;
import com.quanyan.user.utils.ValidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ExecutorService;

/**
 * Created by zhang on 16/7/1.
 */
@Service("userInformationService")
public class UserInformationServiceImpl extends UserBaseServiceImpl implements UserInformationService {

    private final static Logger logger = LoggerFactory.getLogger(UserInformationServiceImpl.class);

    @Autowired
    private TbUserVerifyMapper userVerifyMapper;
    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private TbLevelMapper levelMapper;
    @Autowired
    private TbLevelParamMapper levelParamMapper;
    @Autowired
    private UserTaskService userTaskService;
    @Autowired
    private UserExtService userExtService;
    @Autowired
    private ClubOpenService clubOpenService;
    @Autowired
    private StadiumOpenService stadiumOpenService;
    @Autowired
    private UserTaskMsgClientImpl qcMsgClient;
    @Autowired
    private UserMedalService userMedalService;
    @Autowired
    private UserInterestService userInterestService;
    @Autowired
    private UserQueryService userQueryService;
    @Autowired
    private HttpClientService httpClientService;
    @Autowired
    private AppVersionInfoMapper appVersionInfoMapper;
    @Autowired
    private UserBlacklistService userBlacklistService;
    @Autowired
    private MyRedisTemplate myRedisTemplate;
    @Autowired
    private NewsImagesService newsImagesService;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private UserSmsService userSmsService;
    @Autowired
    private UserDynamicService userDynamicService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private IGatherTagService iGatherTagService;

    @Autowired
    private TbUserFollowMapper tbUserFollowMapper;

    @Autowired
    private TbUserFansMapper tbUserFansMapper;

    @Autowired
    private LevelService levelService;

    @Autowired
    private TbUserFollowMapper userFollowMapper;

    @Autowired
    private CommentServiceFacade commentServiceFacade;

    @Autowired
    private UserService userService;


    @Value("${latestNewsImgNum}")
    private int latestNewsImgNum;
    @Value("${latestUserMedalNum}")
    private int latestUserMedalNum;
    @Value("${quanyan_base_url}")
    private String quanyanBaseUrl;
    @Value("${user_default_icon}")
    private String userDefaultIcon;

    ExecutorService threadPool = ThreadPoolSingleton.getInstance();
    /**
     * 用户实名认证
     * @param reqUserVerify
     * @param uid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean verify(ReqUserVerify reqUserVerify, int uid) {
        String name = StringUtil.replaceBlank(reqUserVerify.getName());
        String idCard = reqUserVerify.getIdCard().trim();
        boolean ver = new IDCard().verify(idCard);
        if (!ver) {
            return ver;
        }
        String idBackImg = reqUserVerify.getIdBackImg();
        String idFrontImg = reqUserVerify.getIdFrontImg();
        int n = this.insertUserVerify(name, idCard, idBackImg, idFrontImg, uid);
        if (n > 0) {
            TbUserExt userExt = this.userExtService.getTbUserExt(uid);
            userExt.setNameVerifyStatus((byte) 1);
            //设置用户完善度标志信息
            UserInfoPerfectStatus userInfoPerfectStatus = this.getUserInfoPerfectStatus(userExt, uid);
            userInfoPerfectStatus.setIsNameVerify(1);
            String json = GsonUtils.toJson(userInfoPerfectStatus);
            userExt.setPerfectStatus(json);
            userExt.setUid(uid);
            boolean flag = userExtService.updateUserExt(userExt);
            return flag;
        }
        threadPool.execute(new UserInformationPerfectDegreeThread(uid, qcMsgClient, userExtService));
        return false;
    }

    /**
     * 获取用户信息
     *
     * @param uid
     * @return
     */
    @Override
    public RespUserInfo getUserInfo(int uid) {
        RespUserInfo respUserInfo = getRespUserPartInfo(uid);
        if (respUserInfo == null) return null;
        
        //设置我的常驻聚集地 //
        RespGatherTags respGatherTags = (RespGatherTags)iGatherTagService.getGatherTags(uid,uid,1).getData();
        if (respGatherTags != null) {
            List<GatherTagItem> gatherTagItems = respGatherTags.getTagItems();
            if (gatherTagItems != null && gatherTagItems.size() >0 ) {
                respUserInfo.setGatherBaseInfos(gatherTagItems);
            }
        }

        return respUserInfo;
    }

    private RespUserInfo getRespUserPartInfo(int uid) {
        TbUser user = userQueryService.getUser(uid);
        if (user == null) {
            return null;
        }
        RespUserInfo respUserInfo = new RespUserInfo();
        respUserInfo.setLarkCode(user.getLarkCode());
        respUserInfo.setName(user.getName());
        respUserInfo.setNickName(user.getNickName());
        respUserInfo.setIcon(user.getIcon());
        respUserInfo.setIsDaren(user.getIsMaster().intValue());
        if (user.getSign() == null) {
            respUserInfo.setSign("");
        } else {
            respUserInfo.setSign(user.getSign());
        }
        if (null == user.getBirthday()) {
            respUserInfo.setBorn(null);
            respUserInfo.setAge(0);
        } else {
            respUserInfo.setBorn(user.getBirthday().getTime());
            respUserInfo.setAge(this.getAge(user.getBirthday()));
        }
        int areaId = 0;
        if (user.getAreaId() != null) {
            areaId = user.getAreaId();
        }
        int provinceId = 0;
        if (user.getProvinceId() != null) {
            provinceId = user.getProvinceId();
        }
        if (provinceId != 0) {
            respUserInfo.setProvinceId(provinceId);
            List<TbProvince> provinceList = super.getProvinceList(provinceId);
            if (!provinceList.isEmpty()) {
                respUserInfo.setProvinceName(provinceList.get(0).getName());
            }
        } else {
            respUserInfo.setProvinceName("");
        }
        if (areaId != 0) {
            respUserInfo.setAreaId(areaId);
            List<TbCity> cityList = super.getCityList(provinceId, areaId);
            if (!cityList.isEmpty()) {
                respUserInfo.setAreaName(cityList.get(0).getName());
            }
        } else {
            respUserInfo.setAreaName("");
        }
        if (user.getRegTime() != null) {
            respUserInfo.setRegTime(user.getRegTime().getTime());
        }
        respUserInfo.setGender(user.getGender());
        respUserInfo.setUid(uid);

        TbUserExt userExt = this.userExtService.getTbUserExt(uid);
        if (userExt != null) {
            respUserInfo.setBgUrl(userExt.getBgUrl());
            respUserInfo.setCompany(userExt.getCompany());
            respUserInfo.setHeight(userExt.getHeight());
            respUserInfo.setWeight(userExt.getWeight());
            respUserInfo.setBmi(userExt.getBmi());
            if (userExt.getPhysique() == null) {
                respUserInfo.setPhysique("");
            } else {
                respUserInfo.setPhysique(userExt.getPhysique());
            }
            respUserInfo.setProfession(userExt.getProfession());

            respUserInfo.setNameVerifyStatus(userExt.getNameVerifyStatus());
            if (userExt.getZodiac() != null) {
                respUserInfo.setZodiac(userExt.getZodiac());
            } else {
                respUserInfo.setZodiac("");
            }

            respUserInfo.setIndustry(userExt.getIndustry());
            if (userExt.getSecondIndustry() == null) {
                respUserInfo.setSecondIndustry("");
            } else {
                respUserInfo.setSecondIndustry(userExt.getSecondIndustry());
            }
        } else {
            respUserInfo.setBgUrl("");
            respUserInfo.setCompany("");
            respUserInfo.setHeight(0);
            respUserInfo.setWeight(0);
            respUserInfo.setBmi(0);
            respUserInfo.setPhysique("");
            respUserInfo.setProfession("");
            respUserInfo.setSign("");
            respUserInfo.setNameVerifyStatus(0);
            respUserInfo.setZodiac("");
            respUserInfo.setIndustry("");
            respUserInfo.setSecondIndustry("");
            respUserInfo.setLarkCode("");
        }

        //设置我的标签
        List<Integer> lableIds = userInfoMapper.getUserLableIds(uid);
        List<LableBaseInfo> lableBaseInfos = null;
        try {
            if (lableIds != null && lableIds.size() > 0) {
                lableBaseInfos = commentServiceFacade.batchTagByIds(lableIds);
                respUserInfo.setLableBaseInfos(lableBaseInfos);
            }

        }catch (Exception e) {
            logger.error("获取标签失败：{}",e);
        }
        // 等级信息
        TbLevel tbLevel = levelService.getTbUserLevel(uid);
        respUserInfo.setLevel((tbLevel != null) ? tbLevel.getLevel() : 0);

        RespCheckDarenAuth respCheckDarenAuth = httpClientService.checkDarenAuth(2,user.getMobile());
        if (respCheckDarenAuth != null && respCheckDarenAuth.isRet() && respCheckDarenAuth.getData() != null && respCheckDarenAuth.getData().isHas_auth()) {
            respUserInfo.setIsDaren(1);
        }
        return respUserInfo;
    }

    /**
     * 更新用户信息
     *
     * @param reqUserInfo
     * @param uid
     * @return
     */
    @Override
    public int updateUserInfo(ReqUserInfo reqUserInfo, int uid) {
        TbUser user = new TbUser();
        TbUserExt userExtDetail = this.userExtService.getTbUserExt(uid);

        UserInfoPerfectStatus userInfoPerfectStatus = this.getUserInfoPerfectStatus(userExtDetail, uid);

        TbUserExt userExt = new TbUserExt();
        userExt.setUid(uid);

        if (reqUserInfo.getNickName() != null) {
            String nickName = reqUserInfo.getNickName();
            user.setNickName(nickName);
            updateUserInfoNotifyMq(uid,MqConstants.UserUpdateType.NICKNAME_UPDATE,nickName);
            logger.debug("用户：【{}】更新了用户昵称,更新时间为：{}",uid,DateUtils.getStandardCurrentTime());
            userInfoPerfectStatus.setIsDefaultNickname(1);
        }
        if (reqUserInfo.getBorn() != null) {
            user.setBirthday(new Date(reqUserInfo.getBorn()));
            userInfoPerfectStatus.setIsDefaultBirthday(1);
            user.setYear(DateUtils.getYear(reqUserInfo.getBorn()));
        }
        if (reqUserInfo.getAreaId() != null && reqUserInfo.getProvinceId() != null) {
            user.setAreaId(reqUserInfo.getAreaId());
            user.setProvinceId(reqUserInfo.getProvinceId());
            userInfoPerfectStatus.setIsDefaultLocation(1);
        }
        if (reqUserInfo.getGender() != null) {
            user.setGender(reqUserInfo.getGender().byteValue());
            userInfoPerfectStatus.setIsDefaultGender(1);
        }
        if (reqUserInfo.getSign() != null) {
            user.setSign(reqUserInfo.getSign());
            userInfoPerfectStatus.setIsDefaultSign(1);
        }
        if (reqUserInfo.getIcon() != null) {
            user.setIcon(reqUserInfo.getIcon());
            userExt.setIsDefaultIcon((byte) 1);
            userInfoPerfectStatus.setIsDefaultIcon(1);
        }
        int n = this.updateUser(user, uid);
        userExt.setBgUrl(reqUserInfo.getBgUrl());
        double height = reqUserInfo.getHeight();
        double weight = reqUserInfo.getWeight();
        //BMI=体重（kg）÷ 身高^2（m）
        if (height != 0) {
            userExt.setHeight(height);
            userExt.setBmi(reqUserInfo.getBmi());
            userExt.setPhysique(reqUserInfo.getPhysique());
            userInfoPerfectStatus.setIsDefaultHeight(1);
        }
        if (weight != 0) {
            userExt.setBmi(reqUserInfo.getBmi());
            userExt.setPhysique(reqUserInfo.getPhysique());
            userExt.setWeight(weight);
            userInfoPerfectStatus.setIsDefaultWeight(1);
        }
        if (reqUserInfo.getIndustry() != null) {
            userExt.setIndustry(reqUserInfo.getIndustry());
            userInfoPerfectStatus.setIsDefaultIndustry(1);
        }
        userExt.setSecondIndustry(reqUserInfo.getSecondIndustry());
        userExt.setCompany(reqUserInfo.getCompany());
        userExt.setProfession(reqUserInfo.getProfession());
        userExt.setZodiac(reqUserInfo.getZodiac());

        String json = GsonUtils.toJson(userInfoPerfectStatus);
        userExt.setPerfectStatus(json);
        boolean flag = false;
        try {
            flag = userExtService.updateUserExt(userExt);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户拓展信息更新异常：uid为【{}】, Exception为【{}】", uid, e);
        }
        threadPool.execute(new UserInformationPerfectDegreeThread(uid, qcMsgClient, userExtService));
        if (flag == false && n == 0) {
            return 0;
        } else {
            return 1;
        }
    }

    /**
     * 我的二维码名片
     *
     * @param uid
     * @return
     */
    @Override
    public RespUserBaseInfo myQRCode(int uid) {

        TbUser user = userQueryService.getUser(uid);
        if (null != user) {
            RespUserBaseInfo respUserBaseInfo = new RespUserBaseInfo();
            respUserBaseInfo.setNickName(user.getNickName());
            respUserBaseInfo.setUid(uid);
            if (null != user.getBirthday()) {
                respUserBaseInfo.setBorn(user.getBirthday().getTime());
            } else {
                respUserBaseInfo.setBorn(0);
            }
            respUserBaseInfo.setGender(user.getGender());
            respUserBaseInfo.setIcon(user.getIcon());
            respUserBaseInfo.setLarkCode(user.getLarkCode());
            respUserBaseInfo.setAge(userQueryService.getCurrentAge(user.getYear() == null ? 0 : user.getYear()));

            RespUserBaseInfo qrParam = new RespUserBaseInfo();
            qrParam.setNickName(user.getNickName());
            qrParam.setUid(uid);
            if (StringUtil.isBlankOrNull(user.getIcon())) {
                qrParam.setIcon(userDefaultIcon);
            } else {
                qrParam.setIcon(user.getIcon());
            }
            String json = GsonUtils.toJson(qrParam);
            String param = Coder.urlEncoder(json.trim());
            StringBuffer sb = new StringBuffer();
            sb.append("http://").append(quanyanBaseUrl).append("?source=bailingniaoqrcode&param=").append(param).append("&type=info");
            String httpResult = ShortUrlUtils.getShortUrl(sb.toString());

            StringBuffer shortUrl = new StringBuffer();

            try {
                if (httpResult != null) {
                    List<RespShareUrl> respShareUrls = JSON.parseArray(httpResult, RespShareUrl.class);
                    shortUrl.append(respShareUrls.get(0).getUrl_short()).append("?source=bailingniaoqrcode&d=").append(uid).append("&m=u");
                }
            } catch (Exception e) {
                logger.error("错误用户uid：【{}】，错误信息：{}",uid,e);
                shortUrl = shortUrl.append("http://").append(quanyanBaseUrl).append("?source=bailingniaoqrcode&d=").append(uid).append("&m=u");
            }
            respUserBaseInfo.setQRCodeUrl(shortUrl.toString());

            return respUserBaseInfo;
        } else {
            return null;
        }
    }

    /**
     * 我的首页信息
     *
     * @param uid
     * @return
     */
    @Override
    public RespUserMine my(int uid, String dsn, int userType) {
        RespUserMine respUserMine = new RespUserMine();
        if (userType == UserConstants.USER_VISITOR) {
            //获取游客兴趣列表（兼容公测版，逐渐淘汰中）
            List<RespUserInterest> userInterestList = userInterestService.getUserSelectInterestIdList(dsn, uid, userType, UserConstants.USER_INTEREST_IS_OBTAIN);
            respUserMine.setInterestList(userInterestList);
            //用户兴趣列表
            List<RespUserSelectInterest> respUserSelectInterestList = userInterestService.getUserSelectInterestList(dsn, uid, userType);
            respUserMine.setUserSelectInterestList(respUserSelectInterestList);
            return respUserMine;
        } else {
            TbUser user = userQueryService.getUser(uid);
            if (user == null) {
                return null;
            }
            respUserMine.setGender(user.getGender());
            respUserMine.setUid(uid);
            respUserMine.setNickName(user.getNickName());
            respUserMine.setIcon(user.getIcon());
            if (user.getBirthday() == null) {
                respUserMine.setBorn(0);
            } else {
                respUserMine.setBorn(user.getBirthday().getTime());
            }
            respUserMine.setLarkCode(user.getLarkCode());
            TbUserExt userExt = userExtService.getTbUserExt(uid);
            if (null != userExt) {
                respUserMine.setBaseState(userExt.getBaseState());
                if (userExt.getZodiac() == null) {
                    respUserMine.setZodiac("");
                } else {
                    respUserMine.setZodiac(userExt.getZodiac());
                }

            } else {
                respUserMine.setBaseState(0);
            }
            /*****************************************用户等级信息开始*****************************************/
            //用户等级
            try {
                TbLevel level = this.getLevel(uid, Constants.LevelType.USER_LEVEL);
                int lev = level.getLevel();
                int xp = level.getXp();
                int nextLevelXp = level.getNextLevelXp();
                int diffXp = nextLevelXp - xp;
                respUserMine.setLevel(lev);
                respUserMine.setCurrentXp(xp);
                respUserMine.setNextLevelXp(nextLevelXp);
                if (diffXp == 0)
                    respUserMine.setLevelRemark("您当前为最高等级");
                else
                   respUserMine.setLevelRemark("还差" + diffXp + "经验达到LV." + (lev + 1));
            } catch (Exception e) {
                //获取个人1级所需经验
                List<TbLevelParam> levelParamList = this.getLevelParam(1, 1);
                if (levelParamList.isEmpty()) {
                    respUserMine.setCurrentXp(0);
                    respUserMine.setNextLevelXp(0);
                    respUserMine.setLevelRemark("还差" + 0 + "经验达到LV.1");
                } else {
                    TbLevelParam levelParam = levelParamList.get(0);
                    respUserMine.setCurrentXp(0);
                    respUserMine.setNextLevelXp(levelParam.getXp());
                    respUserMine.setLevelRemark("还差" + levelParam.getXp() + "经验达到LV.1");
                }
                logger.error("获取用户等级出现异常：用户UID:【{}】,异常信息：【{}】", uid, e.toString());
            }
            /*****************************************用户等级信息结束*****************************************/
            /*****************************************用户兴趣列表开始*****************************************/
            List<RespUserInterest> respUserInterestList = userInterestService.getUserSelectInterestIdList(dsn, uid, userType, UserConstants.USER_INTEREST_IS_OBTAIN);
            List<RespUserSelectInterest> respUserSelectInterestList = userInterestService.getUserSelectInterestList(dsn, uid, userType);
            respUserMine.setUserSelectInterestList(respUserSelectInterestList);
            respUserMine.setInterestList(respUserInterestList);
            /*****************************************用户兴趣列表结束*****************************************/
            /*****************************************用户徽章总数开始*****************************************/
            int count = userMedalService.getUserObtainMedalCount(uid);
            respUserMine.setMedalNum(count);
            /*****************************************用户徽章总数结束*****************************************/
            /*****************************************从C++端获取动态图片数据开始*****************************************/
//            RespMyDynamicImages respMyDynamicImages = newsImagesService.getMyDynamicImages(uid,latestNewsImgNum);
//            respUserMine.setMultimediaNum(respMyDynamicImages.getDynamicCount());
//            respUserMine.setMultimediaList(respMyDynamicImages.getImgInfos());
            List<RespImgInfo> list = userDynamicService.getIndexImgList(uid,uid,latestNewsImgNum);
            //成员动态相册列表
            respUserMine.setMultimediaList(list);
            //成员动态总数
//                respUserIndex.setMultimediaNum(respLatestNews.getTotal());
            respUserMine.setMultimediaNum(userDynamicService.getUserNewsCount(uid,uid));
            /*****************************************从C++端获取动态图片数据结束*****************************************/
            //是否完成新手任务 1 完成 0 未完成
            int n = this.userTaskService.isNewHandComplete(uid);
            respUserMine.setNewbieTaskState(n);
            int foundClubNum = 1;
            int joinClubNum = 1;
            try {
                foundClubNum = this.clubOpenService.getMyManageClubCount(uid);
                joinClubNum = this.clubOpenService.getMyJoinClubCount(uid);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("获取用户加入的和创建的俱乐部的个数出错，异常信息：【{}】", e);
            }
            respUserMine.setFoundClubNum(foundClubNum);
            respUserMine.setJoinClubNum(joinClubNum);
            //加入俱乐部任务URL地址
            List<TbCommonParameter> commonParameterList = super.getCommonParameterList(UserConstants.CLUB_TASK_URL_KEY, null);
            if (commonParameterList.isEmpty()) {
                respUserMine.setClubTaskUrl("");
            } else {
                respUserMine.setClubTaskUrl(commonParameterList.get(0).getParameterValue());
            }
            //更新用户登陆时间
            super.updateUserLoginTime(uid);
            return respUserMine;
        }
    }

    /**
     * 插入用户认证信息
     *
     * @param name
     * @param idCard
     * @param idBackImg
     * @param idFrontImg
     * @param uid
     * @return
     */
    private int insertUserVerify(String name, String idCard, String idBackImg, String idFrontImg, int uid) {
        TbUserVerify userVerify = new TbUserVerify();
        userVerify.setUid(uid);
        userVerify.setIdBackImg(idBackImg);
        userVerify.setIdCard(idCard);
        userVerify.setName(name);
        userVerify.setIdFrontImg(idFrontImg);
        //认证中
        userVerify.setStatus(Constants.UserVerify.USER_VERIFY_DOING);
        int n = this.userVerifyMapper.insertSelective(userVerify);
        return n;
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @Override
    public int updateUser(TbUser user, int uid) {
        user.setId(uid);
        user.setUpdateTime(new Date());
        int m = this.userMapper.updateByPrimaryKeySelective(user);
        if ( m>0 ) {
            logger.info("开始更新缓存：{}，更新的用户为：{}",DateUtils.getStandardCurrentTime(),uid);
            userQueryService.setTbUserRedis(uid);
        }
        //通知c端进行用户信息更新
        httpClientService.updateSetting(uid, null, 3, 1);
        return m;
    }


    /**
     * 检查版本更新
     * @param version
     * @param osType
     * @return
     */
    @Override
    public RespCheckVersion checkVersion(int version, int osType, Integer appType) {
        RespCheckVersion respCheckVersion;
        appType = (appType == null) ? 0 : appType;
        respCheckVersion = (RespCheckVersion) myRedisTemplate.hget(UserConstants.getVersionInfoKey(),UserConstants.getVersionInfoField(version,osType,appType));
        if (respCheckVersion == null) {
            respCheckVersion = new RespCheckVersion();
            List<RespAppVersionInfo> respAppVersionInfoList = this.appVersionInfoMapper.selectAppVersionListByOS(osType,appType, 0, 1);
            if (!respAppVersionInfoList.isEmpty()) {
                RespAppVersionInfo respAppVersionInfo = respAppVersionInfoList.get(0);
                int larkVersionId = respAppVersionInfo.getLarkVersionId();
                if(larkVersionId > version && version >= respAppVersionInfo.getMinVersionId() && version <= respAppVersionInfo.getMaxVersionId()){
                    respCheckVersion.setIsUpdate(1);
                    respCheckVersion.setRespAppVersionInfo(respAppVersionInfo);
                } else {
                    respCheckVersion.setIsUpdate(2);
                }
            } else {
                respCheckVersion.setIsUpdate(2);
            }
            //添加版本信息缓存
            myRedisTemplate.hset(UserConstants.getVersionInfoKey(),UserConstants.getVersionInfoField(version,osType,appType),respCheckVersion);
        }
        return respCheckVersion;
    }

    /**
     * 更换用户手机号
     * @param reqChangePhone
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public APIResponse changePhone(ReqChangePhone reqChangePhone) {
        String phone = StringUtil.replaceBlank(reqChangePhone.getPhone());
        String validCode = reqChangePhone.getValidCode();
        Integer type = reqChangePhone.getType();
        Integer uid = reqChangePhone.getUid();
        if (type.equals(1)) {       //1为对外接口；2为dubbo接口
            APIResponse response = userSmsService.checkCode(validCode,phone);
            boolean flag = response.isRet();
            int errcode = response.getErrcode();
            if (flag && errcode != 200) {
                return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
            }
        }
        if (!ValidUtils.isRegMobile(phone)) {
            return APIResponse.returnFail("您输入的手机号格式有误");
        }
        TbUser user = this.getUserToDbByPhone(phone);
        if (user == null) {
            TbUser oldUser = this.getUserToDbByUid(uid);
            if (oldUser != null ) {
                String oldPhone = oldUser.getMobile();
                TbUser newUser = new TbUser();
                newUser.setMobile(phone);
                int n = updateUser(newUser,uid);
                if(n>0){
                    //删除用户缓存信息
                    String key = UserConstants.getUserRedisKey(uid);
                    String detailKey = UserConstants.getUserDetailRedisKey(uid);
                    RedisKey phoneKey = new RedisKey(UserConstants.FAMILY_MOBILE, oldPhone);//缓存手机号与uid的映射
                    myRedisTemplate.delteKey(key);
                    myRedisTemplate.delteKey(detailKey);
                    //删除uid与手机号的关联缓存
                    myRedisTemplate.delteKey(phoneKey);
                    myRedisTemplate.hdel(UserConstants.UID_MAP, uid.toString().getBytes());
                    myRedisTemplate.hdel(UserConstants.UID_MAP_EXT, uid.toString().getBytes());
                    myRedisTemplate.hdel(UserConstants.UID_MAP_LEVEL, uid.toString().getBytes());
                    //通知业务模块该用户修改了手机号
                    updateUserInfoNotifyMq(uid,MqConstants.UserUpdateType.PHONE_UPDATE,phone);
                    try {
                        APIResponse response = userService.changMobile(phone, uid);
                        if (!response.isRet() || response.getErrcode() != 200) {
                            logger.error("修改手机号第一次通知场馆失败，异常信息：{}",response.getErrmsg());
                            APIResponse response2 = userService.changMobile(phone, uid);
                            if (!response2.isRet() || response2.getErrcode() != 200) {
                                logger.error("修改手机号第二次通知场馆失败，异常信息：{}",response2.getErrmsg());
                                EmailUtils.getInstance().sendTextEmails("fan.song@quncaotech.com","修改手机号通知场馆失败",response2.getErrmsg());
                            }
                        } else {
                            logger.info("用户：【{}】更新了用户手机号,修改时间为：{}",uid,DateUtils.getStandardCurrentTime());
                        }
                    } catch (Exception e) {
                            logger.error("修改手机号通知场馆失败，uid为：{}；手机号为：{}；异常信息：{}",uid,phone,e);
                    }
                    return APIResponse.returnSuccess();
                } else {
                    try {
                        throw new Exception();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return APIResponse.returnFail("手机号修改失败，请重新再试");
                }
            } else {
                return APIResponse.returnFail("您要修改的用户不存在");
            }
        } else {
            return APIResponse.returnFail("该手机号已在百灵鸟注册");
        }
    }

    /**
     * 删除用户缓存
     * @param uid
     * @return
     */
    @Async
    @Override
    public void deleteUserCache(Integer uid) {
        if (uid != null) {
            String key = UserConstants.getUserRedisKey(uid);
            String detailKey = UserConstants.getUserDetailRedisKey(uid);
            myRedisTemplate.delteKey(key);
            myRedisTemplate.delteKey(detailKey);
            myRedisTemplate.hdel(UserConstants.UID_MAP, uid.toString().getBytes());
            myRedisTemplate.hdel(UserConstants.UID_MAP_EXT, uid.toString().getBytes());
            myRedisTemplate.hdel(UserConstants.UID_MAP_LEVEL, uid.toString().getBytes());
        }
    }

    /**
     * 获取用户状态信息
     * @param uid
     * @return
     */
    @Override
    public APIResponse<RespUserState> getUserState(int uid) {
//        int isSignIn = taskEggService.hasObtainedEgg(uid, new Date());
        RespUserState respUserState = new RespUserState();
//        respUserState.setIsSignIn(isSignIn);
        respUserState.setIsSignIn(1);
        return APIResponse.returnSuccess(respUserState);
    }


    /**
     * 我的主页信息
     *
     * @param uid
     * @return
     */
    @Override
    public RespUserIndex index(int uid, String itemType, int currentUid, int userType) {
        RespUserIndex respUserIndex = new RespUserIndex();
        TbUser user = userQueryService.getUser(currentUid);
        if (user == null) {
            return null;
        }
        respUserIndex.setItemType(itemType);
        respUserIndex.setQRCodeUrl("");
        respUserIndex.setIcon(user.getIcon());
        respUserIndex.setLarkCode(user.getLarkCode());

        respUserIndex.setAge(userQueryService.getCurrentAge(user.getYear() == null ? 0 : user.getYear()));
        if (null != user.getBirthday()) {
            respUserIndex.setBorn(user.getBirthday().getTime());
        } else {
            respUserIndex.setBorn(0);
        }
        respUserIndex.setGender(user.getGender());
        respUserIndex.setNickName(user.getNickName());
        respUserIndex.setUid(currentUid);

        TbUserExt userExt = this.userExtService.getTbUserExt(currentUid);
        respUserIndex.setBgUrl(userExt.getBgUrl());
        respUserIndex.setBaseState(userExt.getBaseState());
        respUserIndex.setIsBidsVerify(userExt.getIsBidsVerify());
        respUserIndex.setIsBuyoutVerify(userExt.getIsBuyoutVerify());
        //我管理的俱乐部列表
        List<RespClubOpenInfo> myManageClubList = new ArrayList<>();
        //我加入的俱乐部列表
        List<RespClubOpenInfo> myJoinClubList = new ArrayList<>();
        //用户兴趣列表
        List<RespUserInterest> respUserInterestList = new ArrayList<>();
        //运动名片列表
        List<RespUserCategory> respUserCategoryList = new ArrayList<>();
        if ("sport".equals(itemType)) {   //运动
            /*****************************************从C++端获取动态图片数据开始*****************************************/
            String result = "";
            // dynamic/getUserPhoto.api  最新动态照片和动态总照片数接口
            try {
                result = httpClientService.getAuctionAndDynamicsMsg(currentUid, latestNewsImgNum);
                logger.info("用户动态和竞拍信息返回：{}", result);
                RespBaseModel response = GsonUtils.jsonStrToEntity(result, RespBaseModel.class);
            if(response.isRet() && response.getErrcode() == 200){
                RespLatestNews respLatestNews = response.getData();
//                List<RespImgInfo> list = respLatestNews.getItems();
                List<RespImgInfo> list = userDynamicService.getIndexImgList(uid,currentUid,latestNewsImgNum);
                //成员动态相册列表
                respUserIndex.setMultimediaList(list);
                //成员动态总数
//                respUserIndex.setMultimediaNum(respLatestNews.getTotal());
                respUserIndex.setMultimediaNum(userDynamicService.getUserNewsCount(uid,currentUid));
                //我关注的人
                respUserIndex.setMyConcern(respLatestNews.getFocus_total());
                //我的粉丝
                respUserIndex.setMyFans(respLatestNews.getFans_total());
                //我的竞拍
                RespAuctionInfo respAuctionInfo = new RespAuctionInfo();

                    if (respLatestNews.getAuct_data().getAuctionBaseInfo().getId() != null) {
                        //存在我的竞拍：
                        respUserIndex.setIsHaveBids(1);
                        //竞拍ID
                        respAuctionInfo.setId(respLatestNews.getAuct_data().getAuctionBaseInfo().getId());
                        //竞拍--最新出价
                        respAuctionInfo.setCurMoney(respLatestNews.getAuct_data().getCurMoney());
                        //竞拍--名称
                        respAuctionInfo.setTitle(respLatestNews.getAuct_data().getAuctionBaseInfo().getTitle());
                        //竞拍--封面
                        respAuctionInfo.setCover(respLatestNews.getAuct_data().getAuctionBaseInfo().getCover());
                        if (respLatestNews.getAuct_data().getAuctionBaseInfo().getRespBizPlaceBaseInfo() != null) {
                            //竞拍--场馆
                            respAuctionInfo.setPlaceName(respLatestNews.getAuct_data().getAuctionBaseInfo().getRespBizPlaceBaseInfo().getBizPlaceName());
                        } else {
                            respAuctionInfo.setPlaceName("暂无场馆");
                        }
                        //竞拍--活动开始时间
                        respAuctionInfo.setActivityStartTime(Long.valueOf(respLatestNews.getAuct_data().getAuctionBaseInfo().getActivityStartTime() + "000"));
                        //竞拍--活动结束时间
                        respAuctionInfo.setActivityEndTime(Long.valueOf(respLatestNews.getAuct_data().getAuctionBaseInfo().getActivityEndTime() + "000"));
                        //竞拍--竞拍开始时间
                        respAuctionInfo.setAuctionStartTime(Long.valueOf(respLatestNews.getAuct_data().getAuctionBaseInfo().getAuctionStartTime() + "000"));
                        //竞拍--竞拍结束时间
                        respAuctionInfo.setAuctionEndTime(Long.valueOf(respLatestNews.getAuct_data().getAuctionBaseInfo().getAuctionEndTime() + "000"));
                        //系统当前时间（做前端倒计时）
                        respAuctionInfo.setCurrentTime(Long.valueOf(respLatestNews.getAuct_data().getAuctionBaseInfo().getCurrentTime() + "000"));
                        //竞拍--创建时间
                        respAuctionInfo.setCreateTime(Long.valueOf(respLatestNews.getAuct_data().getAuctionBaseInfo().getCreateTime() + "000"));
                        //竞拍评分
                        respAuctionInfo.setScore(respLatestNews.getAuct_data().getAuctionBaseInfo().getAuctionUserInfo().getScore());

                    } else {
                        //我的竞拍不存在：0
                        respUserIndex.setIsHaveBids(0);
                    }
                    respUserIndex.setRespAuctionInfo(respAuctionInfo);
                }

            } catch (Exception e) {
                logger.error("动态和竞拍信息获取失败：uid为【{}】;返回信息为【{}】;Exception为【{}】", currentUid, result, e);
                //我的竞拍不存在：0
                respUserIndex.setIsHaveBids(0);
            }
            /*****************************************从C++端获取动态图片数据结束*****************************************/
            //用户勋章总数
            int medalNum = super.getUserMedalCount(currentUid);
            respUserIndex.setMedalNum(medalNum);
            //用户勋章列表 ： 勋章type=1为已获得，type=2为未获得
            List<RespUserMedal> respUserMedalList = userMedalService.list(currentUid, currentUid, 1, 0);
            respUserIndex.setRespUserMedalList(respUserMedalList);
            //运动名片列表
            try {
                respUserCategoryList = this.stadiumOpenService.getUserCategoryList(currentUid);
            } catch (Exception e) {
                e.printStackTrace();
            }

            /*****************************************用户资料中的内容开始*****************************************/
            RespUserInfo respUserInfo = new RespUserInfo();
            respUserInfo.setNickName(user.getNickName());
            //星座
            if (userExt.getZodiac() == null) {
                respUserInfo.setZodiac("");
            } else {
                respUserInfo.setZodiac(userExt.getZodiac());
            }
            //出生日期
            if (user.getBirthday() != null) {
                respUserInfo.setBorn(user.getBirthday().getTime());
            } else {
                respUserInfo.setBorn(null);
            }
            int areaId = 0;
            if (user.getAreaId() != null) {
                areaId = user.getAreaId();
            }
            int provinceId = 0;
            if (user.getProvinceId() != null) {
                provinceId = user.getProvinceId();
            }
            //出生地ID
            respUserInfo.setAreaId(areaId);
            respUserInfo.setProvinceId(provinceId);
            //出生地名称
            if (areaId != 0 && provinceId != 0) {
                List<TbCity> cityList = super.getCityList(provinceId, areaId);

                if (!cityList.isEmpty()) {
                    respUserInfo.setAreaName(cityList.get(0).getName());
                }
                List<TbProvince> provinceList = super.getProvinceList(provinceId);
                if (!provinceList.isEmpty()) {
                    respUserInfo.setProvinceName(provinceList.get(0).getName());
                }
            } else {
                respUserInfo.setAreaName("");
                respUserInfo.setProvinceName("");
            }
            //行业
            if (userExt.getIndustry() != null) {
                respUserInfo.setIndustry(userExt.getIndustry());
            } else {
                respUserInfo.setIndustry("");
            }
            //二级行业
            if (userExt.getSecondIndustry() != null) {
                respUserInfo.setSecondIndustry(userExt.getSecondIndustry());
            } else {
                respUserInfo.setSecondIndustry("");
            }
            //个性签名
            respUserInfo.setSign(user.getSign());
            //公司
            if (userExt.getCompany() == null) {
                respUserInfo.setCompany("");
            } else {
                respUserInfo.setCompany(userExt.getCompany());
            }
            //职业
            if (userExt.getProfession() == null) {
                respUserInfo.setProfession("");
            } else {
                respUserInfo.setProfession(userExt.getProfession());
            }

            respUserIndex.setRespUserInfo(respUserInfo);

            //用户等级
            try {
                TbLevel level = this.getLevel(currentUid, Constants.LevelType.USER_LEVEL);
                respUserIndex.setLevel(level.getLevel());
            } catch (Exception e) {
                respUserIndex.setLevel(0);
                logger.error("获取用户等级出现异常：用户UID:【{}】,异常信息：【{}】", uid, e.toString());
            }
            /*****************************************用户资料中的内容结束*****************************************/
            //获取游客兴趣列表（兼容公测版，逐渐淘汰中）
            respUserInterestList = userInterestService.getUserSelectInterestIdList(null, currentUid, UserConstants.USER_REGISTER, UserConstants.USER_INTEREST_IS_OBTAIN);

        } else if ("club".equals(itemType)) {  //俱乐部
            try {
                //我管理的俱乐部列表
                myManageClubList = this.clubOpenService.getMyManageClubList(currentUid);
                //我加入的俱乐部列表
                myJoinClubList = this.clubOpenService.getMyJoinClubList(currentUid);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if ("info".equals(itemType)) {//资料
            //获取游客兴趣列表（兼容公测版，逐渐淘汰中）
            respUserInterestList = userInterestService.getUserSelectInterestIdList(null, currentUid, UserConstants.USER_REGISTER, UserConstants.USER_INTEREST_IS_OBTAIN);
            RespUserInfo respUserInfo = new RespUserInfo();
            respUserInfo.setNickName(user.getNickName());
            //星座
            if (userExt.getZodiac() == null) {
                respUserInfo.setZodiac("");
            } else {
                respUserInfo.setZodiac(userExt.getZodiac());
            }
            //出生日期
            if (user.getBirthday() != null) {
                respUserInfo.setBorn(user.getBirthday().getTime());
            } else {
                respUserInfo.setBorn(null);
            }
            int areaId = 0;
            if (user.getAreaId() != null) {
                areaId = user.getAreaId();
            }
            int provinceId = 0;
            if (user.getProvinceId() != null) {
                provinceId = user.getProvinceId();
            }
            //出生地ID
            respUserInfo.setAreaId(areaId);
            respUserInfo.setProvinceId(provinceId);
            //出生地名称
            if (areaId != 0 && provinceId != 0) {
                List<TbCity> cityList = super.getCityList(provinceId, areaId);

                if (!cityList.isEmpty()) {
                    respUserInfo.setAreaName(cityList.get(0).getName());
                }
                List<TbProvince> provinceList = super.getProvinceList(provinceId);
                if (!provinceList.isEmpty()) {
                    respUserInfo.setProvinceName(provinceList.get(0).getName());
                }
            } else {
                respUserInfo.setAreaName("");
                respUserInfo.setProvinceName("");
            }
            //行业
            if (userExt.getIndustry() != null) {
                respUserInfo.setIndustry(userExt.getIndustry());
            } else {
                respUserInfo.setIndustry("");
            }
            //二级行业
            if (userExt.getSecondIndustry() != null) {
                respUserInfo.setSecondIndustry(userExt.getSecondIndustry());
            } else {
                respUserInfo.setSecondIndustry("");
            }
            //个性签名
            respUserInfo.setSign(user.getSign());
            //公司
            if (userExt.getCompany() == null) {
                respUserInfo.setCompany("");
            } else {
                respUserInfo.setCompany(userExt.getCompany());
            }
            //职业
            if (userExt.getProfession() == null) {
                respUserInfo.setProfession("");
            } else {
                respUserInfo.setProfession(userExt.getProfession());
            }
            respUserIndex.setRespUserInfo(respUserInfo);
            //用户等级
            try {
                TbLevel level = this.getLevel(currentUid, Constants.LevelType.USER_LEVEL);
                respUserIndex.setLevel(level.getLevel());
            } catch (Exception e) {
                respUserIndex.setLevel(0);
                logger.error("获取用户等级出现异常：用户UID:【{}】,异常信息：【{}】", uid, e);
            }
        }
        /*****************************************用户俱乐部列表开始*****************************************/
        respUserIndex.setMyManageClubList(myManageClubList);
        respUserIndex.setMyJoinClubList(myJoinClubList);
        List<RespUserSelectInterest> respUserSelectInterestList = this.userInterestService.getUserSelectInterestList(null, currentUid, UserConstants.USER_REGISTER);
        respUserIndex.setRespUserSelectInterestList(respUserSelectInterestList);
        respUserIndex.setRespUserInterestList(respUserInterestList);
        respUserIndex.setRespUserCategoryList(respUserCategoryList);
        /*****************************************用户俱乐部列表结束*****************************************/
        if (userType == UserConstants.USER_REGISTER) {
            if (uid != currentUid) {  //其他人主页
                //查看用户是否被加入了黑名单
                TbUserBlacklist userBlacklist = userBlacklistService.getUserIsBlack(uid,currentUid);
                if (null != userBlacklist) {
                    respUserIndex.setIsBlack(1);
                } else {
                    respUserIndex.setIsBlack(0);
                }
                /*****************************************从C++端获取用户间关系开始*****************************************/
//                String result = "";
//                try {
//                    result = httpClientService.getUserRelationInfo(currentUid, uid);
//                    RespUserRelationModel response = GsonUtils.jsonStrToEntity(result, RespUserRelationModel.class);
//                    if (response.isRet() && response.getErrcode() == 200 ) {
//                        //1：关注,2：粉丝,3：好友,4：无关系（陌生人）
//                        respUserIndex.setRelationType(response.getData().getRelationType());
//                        respUserIndex.setRemark(response.getData().getRemark());
//                    } else {
//                        respUserIndex.setRelationType(4);
//                        respUserIndex.setRemark("");
//                    }
//                } catch (Exception e) {
//                    logger.error("个人主页获取用户关系失败;uid为【{}】;返回信息为【{}】;异常信息为【{}】", uid, result, e);
//                    e.printStackTrace();
//                    respUserIndex.setRelationType(4);
//                    respUserIndex.setRemark("");
//                }
                //TODO:待调试
                UserRelation userRelation = userRelationService.getUserRelationType(uid, currentUid);
                //1：关注,2：粉丝,3：好友,4：无关系（陌生人）
                respUserIndex.setRelationType(userRelation.getRelationType());
                respUserIndex.setRemark(userRelation.getRemark());
                /*****************************************从C++端获取用户间关系结束*****************************************/
            }
        } else if (userType == UserConstants.USER_VISITOR) {
            respUserIndex.setRelationType(4);
            respUserIndex.setRemark("");
            respUserIndex.setIsBlack(0);
        }
        return respUserIndex;
    }

    /**
     * 省市列表
     *
     * @return
     */
    @Override
    public RespSituation situation() {
        RespSituation respSituation = new RespSituation();
        List<TbProvince> provinceList = super.getProvinceList(0);
        List<RespUserProvince> respUserProvinceList = new ArrayList<>();
        if (!provinceList.isEmpty()) {

            RespUserProvince respUserProvince;
            for (TbProvince tbProvince : provinceList) {
                respUserProvince = new RespUserProvince();
                respUserProvince.setProvinceId(tbProvince.getId());
                respUserProvince.setProvinceName(tbProvince.getName());
                respUserProvince.setPriority(tbProvince.getPriority());
                List<TbCity> cityList = super.getCityList(tbProvince.getId(), 0);
                List<RespUserCity> respUserCityList = new ArrayList<>();
                if (!cityList.isEmpty()) {
                    RespUserCity respUserCity;
                    for (TbCity tbCity : cityList) {
                        respUserCity = new RespUserCity();
                        respUserCity.setCityId(tbCity.getId());
                        respUserCity.setCityName(tbCity.getName());
                        respUserCityList.add(respUserCity);
                    }
                    respUserProvince.setRespCityList(respUserCityList);
                } else {
                    respUserProvince.setRespCityList(respUserCityList);
                }
                respUserProvinceList.add(respUserProvince);
            }
            respSituation.setProvinceList(respUserProvinceList);
        } else {
            respSituation.setProvinceList(respUserProvinceList);
        }
        return respSituation;
    }

    /**
     * 更新用户基础信息
     *
     * @param requestBaseParam
     * @param uid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int updateUserBaseInfo(ReqUserBaseParam requestBaseParam, int uid) {
        TbUserExt userExt = userExtService.getTbUserExt(uid);
        UserInfoPerfectStatus userInfoPerfectStatus = this.getUserInfoPerfectStatus(userExt, uid);
        TbUser user = new TbUser();
        user.setIcon(requestBaseParam.getIcon());
        userInfoPerfectStatus.setIsDefaultIcon(1);
        user.setGender(requestBaseParam.getGender().byteValue());
        userInfoPerfectStatus.setIsDefaultGender(1);
        long born = requestBaseParam.getBorn();
        user.setBirthday(new Date(born));
        userInfoPerfectStatus.setIsDefaultBirthday(1);
        user.setYear(DateUtils.getYear(born));
        user.setNickName(requestBaseParam.getNickName());
        userInfoPerfectStatus.setIsDefaultNickname(1);
        String json = GsonUtils.toJson(userInfoPerfectStatus);
        int n = this.updateUser(user, uid);
        if (n > 0) {
            userExt.setZodiac(requestBaseParam.getZodiac());
            userExt.setBaseState((byte) 1);
            userExt.setIsDefaultIcon((byte) 1);
            userExt.setPerfectStatus(json);
            userExt.setUid(uid);
            this.userExtService.updateUserExt(userExt);
            threadPool.execute(new UserInformationPerfectDegreeThread(uid, qcMsgClient, userExtService));
        }
        return n;
    }

    /**
     * 获取用户公共参数
     *
     * @param map
     * @return
     */
    @Override
    public List<RespCommonParameter> parameter(Map map) {
        String parameterKey = (String) map.get("parameterKey");
        String extendInfo = null;
        if (map.containsKey("extendInfo")) {
            extendInfo = (String) map.get("extendInfo");
        }
        List<TbCommonParameter> commonParameterList = super.getCommonParameterList(parameterKey, extendInfo);
        List<RespCommonParameter> respCommonParameterList = new ArrayList<>();
        if (!commonParameterList.isEmpty()) {
            RespCommonParameter respCommonParameter;
            for (TbCommonParameter tbCommonParameter : commonParameterList) {
                respCommonParameter = new RespCommonParameter();
                respCommonParameter.setParameterValue(tbCommonParameter.getParameterValue());
                respCommonParameter.setExtendInfo(tbCommonParameter.getExtendInfo());
                respCommonParameter.setName(tbCommonParameter.getName());
                respCommonParameterList.add(respCommonParameter);
            }
        }
        return respCommonParameterList;
    }

    /**
     * 获取等级信息
     *
     * @param commonId
     * @param type
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public TbLevel getLevel(int commonId, byte type) {
        TbLevelExample example = new TbLevelExample();
        TbLevelExample.Criteria criteria = example.createCriteria();
        criteria.andCommonIdEqualTo(commonId);
        criteria.andTypeEqualTo(type);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbLevel> list = this.levelMapper.selectByExample(example);
        if (list.isEmpty()) {
            TbLevel level = new TbLevel();
            level.setCommonId(commonId);
            level.setLevel(0);
            level.setXp(0);
            level.setType(Constants.BYTE_ONE);
            //获取个人1级所需经验
            List<TbLevelParam> levelParamList = this.getLevelParam(1, 1);
            if (levelParamList.isEmpty()) {
                level.setNextLevelXp(0);
            } else {
                level.setNextLevelXp(levelParamList.get(0).getXp());
            }
            this.levelMapper.insertSelective(level);
            return level;
        } else {
            return list.get(0);
        }
    }

    /**
     * 获取等级参数信息
     *
     * @param level
     * @param type
     * @return
     */
    private List<TbLevelParam> getLevelParam(Integer level, Integer type) {
        TbLevelParamExample example = new TbLevelParamExample();
        TbLevelParamExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andTypeEqualTo(type.byteValue());
        criteria.andLevelEqualTo(level);
        List<TbLevelParam> levelParamList = this.levelParamMapper.selectByExample(example);
        return levelParamList;
    }


    /**
     * 获取用户完善度状态信息
     *
     * @param userExt
     * @return
     */
    private UserInfoPerfectStatus getUserInfoPerfectStatus(TbUserExt userExt, Integer uid) {
        UserInfoPerfectStatus userInfoPerfectStatus;
        if (StringUtil.isBlankOrNull(userExt.getPerfectStatus())) {
            userInfoPerfectStatus = new UserInfoPerfectStatus();
            TbUser user = this.userQueryService.getUser(uid);
            if (user != null) {
                if (user.getNickName() != null && !user.getNickName().equals(LarkCodeUtil.generateDefaultNickName(user.getMobile()))) {
                    userInfoPerfectStatus.setIsDefaultNickname(1);
                }
                if (user.getBirthday() != null) {
                    userInfoPerfectStatus.setIsDefaultBirthday(1);
                }
                if (user.getGender() != 0) {
                    userInfoPerfectStatus.setIsDefaultGender(1);
                }
                if (!StringUtil.isBlankOrNull(user.getIcon())) {
                    userInfoPerfectStatus.setIsDefaultIcon(1);
                }
            }
        } else {
            userInfoPerfectStatus = GsonUtils.jsonStrToEntity(userExt.getPerfectStatus(), UserInfoPerfectStatus.class);
        }
        return userInfoPerfectStatus;
    }

    /**
     * 发送用户修改信息通知
     * @param uid
     * @param updateType
     */
    public void updateUserInfoNotifyMq(int uid,int updateType,Object updateObj){
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setMsgId(String.valueOf(System.currentTimeMillis()));
        mqRequestMsg.setTopic(MqConstants.UserUpdateTopicAndTags.USER_UPDATE_NOTIFY_TOPIC);
        mqRequestMsg.setTag(MqConstants.UserUpdateTopicAndTags.USER_UPDATE_NOTIFY_TAGS);

        UserUpdateNotifyMsg userUpdateNotifyMsg = new UserUpdateNotifyMsg();
        userUpdateNotifyMsg.setUid(uid);
        userUpdateNotifyMsg.setUpdateType(updateType);
        userUpdateNotifyMsg.setUpdateTime(new Date());
        userUpdateNotifyMsg.setUpdateObj(updateObj);

        mqRequestMsg.setBody(ObjectUtil.toByteArray(userUpdateNotifyMsg));
        qcMsgClient.asyncSend(mqRequestMsg);

    }

    @Override
    public APIResponse<List<LableBaseInfo>> randomGenerateLables(Integer pageSize) {
        if (pageSize == null || pageSize <= 0 ) {
            return APIResponse.returnFail("请传入必要参数");
        }
        try {
            return APIResponse.returnSuccess(commentServiceFacade.randTags(pageSize));
        }catch (Exception e) {
            logger.error("随机获取一批标签失败：{}", e.getMessage());
            return APIResponse.returnFail("随机获取一批标签失败");
        }
    }


    @Override
    public boolean editUserInfo(Integer uid, ReqEditUserInfoParam editUserInfoParam) {
        TbUser user = new TbUser();
        TbUserExt userExtDetail = this.userExtService.getTbUserExt(uid);
        UserInfoPerfectStatus userInfoPerfectStatus = this.getUserInfoPerfectStatus(userExtDetail, uid);

        String nickName = editUserInfoParam.getNickName();
        if (nickName != null) {
            user.setNickName(nickName);
            updateUserInfoNotifyMq(uid, MqConstants.UserUpdateType.NICKNAME_UPDATE, nickName);
            userInfoPerfectStatus.setIsDefaultNickname(1);
        }
        Long born = editUserInfoParam.getBorn();
        if (born != null) {
            user.setBirthday(new Date(born));
            userInfoPerfectStatus.setIsDefaultBirthday(1);
            user.setYear(DateUtils.getYear(born));
        }

        Byte gender = editUserInfoParam.getGender();
        if (gender != null) {
            user.setGender(gender.byteValue());
            userInfoPerfectStatus.setIsDefaultGender(1);
        }

        String sign = editUserInfoParam.getSign();
        if (sign != null) {
            user.setSign(sign);
            userInfoPerfectStatus.setIsDefaultSign(1);
        }

        TbUserExt userExt = new TbUserExt();
        userExt.setUid(uid);

        String icon = editUserInfoParam.getIcon();
        if (icon != null) {
            user.setIcon(icon);
            userExt.setIsDefaultIcon((byte) 1);
            userInfoPerfectStatus.setIsDefaultIcon(1);
        }
        int n = this.updateUser(user, uid);
        userExt.setBgUrl(editUserInfoParam.getBgUrl());
        double height = editUserInfoParam.getHeight();
        double weight = editUserInfoParam.getWeight();
        if (height != 0) {
            userExt.setHeight(height);
            userInfoPerfectStatus.setIsDefaultHeight(1);
        }
        if (weight != 0) {
            userExt.setWeight(weight);
            userInfoPerfectStatus.setIsDefaultWeight(1);
        }

        String industry = editUserInfoParam.getIndustry();
        if (industry != null) {
            userExt.setIndustry(industry);
            userInfoPerfectStatus.setIsDefaultIndustry(1);
        }

        userExt.setSecondIndustry(editUserInfoParam.getSecondIndustry());
        userExt.setCompany(editUserInfoParam.getCompany());
        userExt.setProfession(editUserInfoParam.getProfession());

        String json = GsonUtils.toJson(userInfoPerfectStatus);
        userExt.setPerfectStatus(json);
        boolean flag = userExtService.updateUserExt(userExt);

        //设置用户标签
        List<Integer> labelIds = editUserInfoParam.getLabelIds();
        if (labelIds != null && labelIds.size() > 0) {
            userInfoMapper.deleteUserLabel(uid);
            userInfoMapper.batchIntoUserLabel(labelIds,uid);
        }

        if (labelIds != null && labelIds.isEmpty()) {
            userInfoMapper.deleteUserLabel(uid);
        }

        //设置用户聚集地信息
        List<Integer> gatherPlaceIds = editUserInfoParam.getGatherPlaceIds();
        if (gatherPlaceIds != null) {
            iGatherTagService.editGatherTags(uid,gatherPlaceIds);
        }
        if (flag ) {
            threadPool.execute(new UserInformationPerfectDegreeThread(uid, qcMsgClient, userExtService));
        }

        return flag;
    }

    /**
     * 用户主页
     *
     * @param uid 用户id
     * @return
     */
    @Override
    public APIResponse getUserIndex(Integer uid, Integer taUid) {
        UserIndex userIndex = new UserIndex();

        try {
            if (uid != null && taUid != null ) {   //我的主页
                if (uid.intValue() ==  taUid.intValue() ) {
                    setUserIndexInfo(uid, userIndex);
                    if (userIndex.getRespUserInfo() != null ) {
                        //设置我的常驻聚集地 //
                        RespGatherTags respGatherTags = iGatherTagService.getGatherTags(uid,uid,1).getData();
                        if (respGatherTags != null) {
                            List<GatherTagItem> gatherTagItems = respGatherTags.getTagItems();
                            if (gatherTagItems != null && gatherTagItems.size() >0 ) {
                                userIndex.getRespUserInfo().setGatherBaseInfos(gatherTagItems);
                            }
                        }
                    }
                }
            }

            if (uid != null && taUid != null ) {
                if (taUid.intValue() != uid.intValue()) {     //她的主页
                    setUserIndexInfo(taUid, userIndex);

                    //设置我的常驻聚集地 //
                    if (userIndex.getRespUserInfo() != null ) {
                        RespGatherTags respGatherTags = iGatherTagService.getGatherTags(uid,taUid, 1).getData();
                        if (respGatherTags != null) {
                            List<GatherTagItem> gatherTagItems = respGatherTags.getTagItems();
                            if (gatherTagItems != null && gatherTagItems.size() >0 ) {
                                userIndex.getRespUserInfo().setGatherBaseInfos(gatherTagItems);
                            }
                        }
                    }

                    if (uid != null && uid > 0 ) {
                        TbUserFollow tbUserFollow = userFollowService.getTbUserFollow(uid, taUid);
                        if (tbUserFollow != null ) {
                            userIndex.setIsfollow(1);
                        }
                    }

                    TbUserBlacklist userBlacklist = userBlacklistService.getUserIsBlack(uid,taUid);
                    if (null != userBlacklist) {
                        userIndex.setIsBlack(1);
                    }

                    //设置备注名
                    TbUserFollowExample exampleFollow = new TbUserFollowExample();
                    TbUserFollowExample.Criteria criteriaFollow = exampleFollow.createCriteria();
                    criteriaFollow.andUidEqualTo(uid);
                    criteriaFollow.andFollowIdEqualTo(taUid);
                    criteriaFollow.andStateEqualTo((byte)0);

                    List<TbUserFollow> tbUserFollowList = userFollowMapper.selectByExample(exampleFollow);
                    if(tbUserFollowList != null && tbUserFollowList.size() > 0){
                        userIndex.setRemark(tbUserFollowList.get(0).getComment());
                    }
                }
            }

            if (uid == null && taUid != null) {            //她的主页
                setUserIndexInfo(taUid, userIndex);

                //设置我的常驻聚集地
                if (userIndex.getRespUserInfo() != null ) {
                    RespGatherTags respGatherTags = iGatherTagService.getGatherTags(0,taUid, 1).getData();
                    if (respGatherTags != null) {
                        List<GatherTagItem> gatherTagItems = respGatherTags.getTagItems();
                        if (gatherTagItems != null && gatherTagItems.size() >0 ) {
                            userIndex.getRespUserInfo().setGatherBaseInfos(gatherTagItems);
                        }
                    }
                }
            }

        }catch (Exception e) {
            logger.error("获取用户主页信息失败:{}",e);
            return APIResponse.returnFail("获取用户主页信息失败");
        }

        return APIResponse.returnSuccess(userIndex);
    }

    private void setUserIndexInfo(Integer uid, UserIndex userIndex) {
        RespUserInfo respUserInfo = getRespUserPartInfo(uid);
        userIndex.setRespUserInfo(respUserInfo);   //设置用户基本信息

        try {
            MyNewestClubCard myNewestClubCard = clubOpenService.getMyNewestClub(uid);
            if (myNewestClubCard != null ) {
                ClubInfo clubInfo = new ClubInfo();
                clubInfo.setTotalCount(myNewestClubCard.getTotalCount());
                clubInfo.setCityName(myNewestClubCard.getCityName());
                clubInfo.setClubLogo(myNewestClubCard.getClubLogo());
                clubInfo.setClubName(myNewestClubCard.getClubName());
                clubInfo.setDistinctName(myNewestClubCard.getDistinctName());
                clubInfo.setMemberCount(myNewestClubCard.getMemberCount());
                userIndex.setClubInfo(clubInfo);
            }

        } catch (Exception e){
            logger.error("获取俱乐部信息失败：{}",e);
            ClubInfo clubInfo = new ClubInfo();
            clubInfo.setTotalCount(0);
            userIndex.setClubInfo(clubInfo);
        }
        RespMyDynamicImages dynamicImages = newsImagesService.getMyDynamicImages(uid,3);
        userIndex.setMyDynamic(dynamicImages);    //设置动态信息
        userIndex.setDoyenActivity(httpClientService.getDoyenActivity(uid));  //设置达人活动

        TbUserFansExample  fansExample = new TbUserFansExample();
        TbUserFansExample.Criteria fansCriteria = fansExample.createCriteria();
        fansCriteria.andUidEqualTo(uid);
        fansCriteria.andStateEqualTo((byte)0);
        int fansCount = tbUserFansMapper.countByExample(fansExample);

        TbUserFollowExample followExample = new TbUserFollowExample();
        TbUserFollowExample.Criteria followCriteria =  followExample.createCriteria();
        followCriteria.andStateEqualTo((byte)0);
        followCriteria.andUidEqualTo(uid);
        int followCount = tbUserFollowMapper.countByExample(followExample);

        userIndex.setFansCount(fansCount);      //设置用户粉丝数
        userIndex.setFollowCount(followCount);  //设置用户关注数
    }


    /**
     * 根据生日获取年龄
     *
     * @param birthDay
     * @return
     */
    private Integer getAge(Date birthDay ){
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
           return 0;
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;//注意此处 +1
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH) + 1;  //注意此处 +1
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow == monthBirth) {
            if (dayOfMonthNow < dayOfMonthBirth) {
                age--;
            }

        } else if (monthNow < monthBirth) {
            age--;
        }

        return age;
    }


    @Override
    public APIResponse updateUserRedis(List<Integer> uids) {
        for(Integer uid : uids){
            userQueryService.setTbUserRedis(uid);
        }

        return APIResponse.returnSuccess();
    }

    @Override
    public boolean isUserEnable(Integer uid) {
        TbUserExample userExample = new TbUserExample();
        TbUserExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andIsEnableEqualTo((byte)1);    //可用
        userCriteria.andIdEqualTo(uid);
        List<TbUser> users = userMapper.selectByExample(userExample);
        if (users != null && users.size() > 0 ) {
            return true;       //可用
        }
        return false;    //不可用
    }

}
